<template>
  <div class="bg-white">
    <van-tabs v-if="types.length !== 0" @change="tabChange" type="card" :ellipsis="false">
      <van-tab v-for="item in types" :key="item.id" :title="item.gtype">
        <van-list
          v-model="listControl.loading"
          :finished="listControl.pages === 0 || listPage.current === listControl.pages"
          finished-text="没有更多了"
          @load="getMoreData()"
          :immediate-check="false"
        >
          <goods-list :list="list" @changeGoodsStatus="changeGoodsStatus"></goods-list>
        </van-list>
        <empty-data class="text-center m-t-20" v-if="!list.length && ready" content="暂无数据"></empty-data>
      </van-tab>
    </van-tabs>
    <div v-if="types.length === 0">
      <empty-data class="text-center m-t-20" content="暂无数据"></empty-data>
    </div>
  </div>
</template>

<script>
import GoodsList from '@/views/Index/components/GoodsList'
export default {
  props: {
    bid: {
      required: true
    }
  },
  data () {
    return {
      ready: false,
      type: '',
      types: [],
      list: [],
      listPage: {
        size: 10,
        current: 1
      },
      listControl: {
        pages: null,
        loading: false
      }
    }
  },
  components: {
    GoodsList
  },
  mounted () {
    this.init()
  },
  methods: {
    async init () {
      await this.getTypes()
      this.type = this.types.length ? this.types[0].gtype : ''
      this.type && this.getMerchantGoods()
    },
    changeGoodsStatus ({ id }) {
      this.list.forEach(d => {
        if (d.id === id) {
          d.hasGetDiscounts = true
        }
      })
    },
    getMoreData () {
      // 分页查询附近商家
      this.listPage.current++
      this.getMerchantGoods()
    },
    async getTypes () {
      let { zxBsGtList } = await this.$api.post('/bsGt/query', {
        bid: this.bid
      })
      this.types = zxBsGtList
    },
    async getMerchantGoods () {
      this.ready = false
      this.listControl.loading = true
      let { page } = await this.$api.post('/zxGd/query', {
        bid: this.bid,
        size: 10,
        current: this.listPage.current,
        gtype: this.type
      })
      let { pages, current, records } = page
      records.forEach(d => {
        d.hasGetDiscounts = false
      })
      this.listPage.current = current
      this.listControl.pages = pages
      this.listControl.loading = false
      this.list = [...this.list, ...records]
      this.ready = true
    },
    async tabChange (item, title) {
      this.listPage = {
        size: 10,
        current: 1
      }
      this.listControl = {
        pages: null,
        loading: false
      }
      this.type = title
      this.list = []
      this.getMerchantGoods()
    }
  }
}
</script>

<style lang="scss" scoped>
.a-s-start {
  align-self: flex-start;
}
</style>
